<template>
  <div>
    <ft-user-head
      field="img"
      :width="150"
      :height="150"
      :url="getUploader()"
      :headers="headers"
      :noRotate="true"
      v-model="cutting"
      ref="userHeadRef"
      @close="showImgShear(false)"
      img-format="jpg">
    </ft-user-head>
    <img ref="image" class="avatar" @click="showImgShear(true)"
         src="../../static/img/head0.jpg"/>
  </div>
</template>

<script>
  import FtUserHead from "./UserHead/FtUserHead";

  export default {
    name: "UserHead",
    props: ['value', 'userId'],
    components: {FtUserHead},
    data() {
      return {
        cutting: false,
        imgSrc: null,
        headers: {
          'Content-Type': 'multipart/form-data',
          'AUTH-TOKEN': localStorage.getItem('AUTH-TOKEN'),
          'Accept': 'application/json',
        }
      }
    },
    methods: {
      getUploader() {
        return '/joys-rest/joys-file/file/upload?sourceId=' + this.userId + '&dirName=/user&one2one=true&overwrite=true'
      },
      showImgShear(value) {
        if (this.userId) {
          this.cutting = value
          if (!value) {
            this.loadImg()
          }
        } else {
          this.$message.info('请先保存用户信息!')
        }
      },
      loadImg() {
        this.$http.get('/joys-rest/joys-file/thumb/byThumb/Single?sourceId=' + this.userId).then(resp => {
          this.imgSrc = resp.bodyText
          if (resp.bodyText) {
            this.$refs.image.src = this.imgSrc
          } else {
            this.$refs.image.src = require('../../static/img/head0.jpg')
          }
        }, resp => {
          this.$message.error(resp.body.message)
        })
      }

    },
    watch: {
      userId() {
        this.loadImg()
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    line-height: 0px;
  }

  .avatar-uploader:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    line-height: 108px;
    text-align: center;
  }

  .avatar {
    width: 108px;
    height: 108px;
    display: inline-block;
  }
</style>

